#!/usr/bin/env python

import sys;
import MySQLdb as ordbms

class CleanUp:

	def __init__(self, hostname, username, password, database):
		self.conn = ordbms.connect (host = hostname,
			user = username,
			passwd = password,
			db = database)

		self.cursor = self.conn.cursor ()
		self.twocursor = self.conn.cursor ()


	def doit(self):
		self.cursor.execute("SELECT artist from Scrobbles;");

		while (1):
			row = self.cursor.fetchone()
			if row == None:
				break

			oldname = row[0]
			newname = oldname

			if "\'" in row[0]:
				newname = row[0].replace("\\'","'")

			if "&amp;" in oldname:
				newname = newname.replace("&amp;","&")

			if "&quot;" in oldname:
				newname = newname.replace("&quot;","\"")

			if "&lt;" in oldname:
				newname = newname.replace("&lt;","<")

			if "&gt;" in oldname:
				newname = newname.replace("&gt;",">")

			if " (PREVIEW: buy it at www.magnatune.com)" in oldname:
				newname = newname.replace(" (PREVIEW: buy it at www.magnatune.com)","")

			if oldname <> newname:
				print "%s >>>INTO>>> %s" % (oldname, newname)
				try:
					self.twocursor.execute("UPDATE Scrobbles SET artist = %s WHERE artist = %s", (newname, oldname))
					self.twocursor.execute("DELETE FROM Artist WHERE name = %s", (oldname))
				except Exception, e:
					print e


	def close(self):
		self.cursor.close()
		self.conn.commit()
		self.conn.close()


	def artist_exists(self, artist):
		try:
			self.cursor.execute("SELECT name FROM Artist WHERE name = %s ", (artist,))
			return self.cursor.rowcount != 0
		except:
			return False

if __name__ == "__main__":

	if len(sys.argv) != 5:
		print "Usage: scrobbles-revisionism <mysql hostname> <mysql username> <mysql password> <mysql database>"
		sys.exit(1)
	
	cleaner = CleanUp(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
	cleaner.doit()
	cleaner.close()
